package com.renwei.yunlong.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.renwei.yunlong.bean.LoginBean;
import com.renwei.yunlong.bean.ServiceLoginBean;
import com.renwei.yunlong.event.ReceiveLocationEvent;
import com.renwei.yunlong.event.SendLocationEvent;
import com.renwei.yunlong.http.HttpPresenter;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.ACache;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.LogUtil;
import com.renwei.yunlong.http.Api;

import java.util.HashMap;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

/**
 * Created by wangqi on 2017/10/17.
 */

public class LocationService extends Service {

    private LocationClient mLocationClient;
    private ACache mCache;
    private LoginBean ownerBean;
    private ServiceLoginBean serviceBean;
    private String companyType;
    private BDLocation location;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        // 在使用 SDK 各组间之前初始化 context 信息，传入 ApplicationContext
//        SDKInitializer.initialize(this);
        //自4.3.0起，百度地图SDK所有接口均支持百度坐标和国测局坐标，用此方法设置您使用的坐标类型.
        //包括BD09LL和GCJ02两种坐标，默认是BD09LL坐标。
//        SDKInitializer.setCoordType(CoordType.BD09LL);
        //声明LocationClient类
        EventBus.getDefault().register(this);

        if (mLocationClient == null) {
            mLocationClient = new LocationClient(getApplicationContext());
            mLocationClient.registerLocationListener(new MyLocationListener());
            initLocation();
        }
    }

    @Subscribe(threadMode = ThreadMode.BackgroundThread)
    public void onSendLocationEvent(SendLocationEvent event) {
        EventBus.getDefault().post(new ReceiveLocationEvent(location));
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 开启服务 后台上传
        if (mLocationClient != null) {
            mLocationClient.start();
            LogUtil.e("后台定位服务开启");
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (mLocationClient != null) {
            mLocationClient.stop();
        }
    }

    public class MyLocationListener implements BDLocationListener {
        int time = 300; //5分钟

        @Override
        public void onReceiveLocation(BDLocation location) {
//            LogUtil.e(location.getLatitude()+"---"+location.getLongitude());
            if (4.9E-324 == location.getLatitude() || 4.9E-324 == location.getLongitude()) {
               // LogUtil.e("location","定位权限关闭");
                return;
            }
            LocationService.this.location = location;

            if (time == 300) {
                mCache = ACache.get(LocationService.this);
                ownerBean = (LoginBean) mCache.getAsObject("loginBean");
                serviceBean = (ServiceLoginBean) mCache.getAsObject("serviceLoginBean");
                companyType = mCache.getAsString("companyType");
                //开始上传、
                upload(location.getLatitude() + "", location.getLongitude() + "");
            }
            time--;
            if (time == 0) {
                time = 300;
            }
        }

    }

    /**
     * 上传本地位置信息
     *
     * @param latitude
     * @param longitude
     */
    private void upload(String latitude, String longitude) {
        HttpPresenter hp = new HttpPresenter(this);
        HashMap<String, String> map = new HashMap<>();
        map.put("longitude", longitude);
        map.put("latitude", latitude);
        if ("1".equals(companyType)) {
            hp.setUrl(Api.$().OWNER_SAVE_LOCATION);
            map.put("ownerCode", ownerBean.getRows().getOwnerCode());
            map.put("currentUserId", ownerBean.getRows().getEmployeeId());
            hp.putParam("jsonBean", JsonMapUtil.mapToJson(map));
        } else if ("2".equals(companyType)) {
            hp.setUrl(Api.$().SERVICE_SAVE_LOCATION);
            map.put("serviceProviderCode", serviceBean.getRows().getServiceProviderCode());
            map.put("currentUserId", serviceBean.getRows().getEmployeeId());
            hp.putParam("jsonBean", JsonMapUtil.mapToJson(map));
        }
        hp.setShowDialog(false);
        hp.setCallBack(new HttpTaskListener() {
            @Override
            public void onSuccess(int requestId, String result) {
            }

            @Override
            public void onException(int requestId, String code) {
                LogUtil.e("后台服务开启失败 " + code);
            }
        });
        hp.post();
    }

    private void initLocation() {

        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，默认高精度，设置定位模式，高精度，低功耗，仅设备

        option.setCoorType("bd09ll");
        //可选，默认gcj02，设置返回的定位结果坐标系

        int span = 1000;
        option.setScanSpan(span);
        //可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的

        option.setIsNeedAddress(true);
        //可选，设置是否需要地址信息，默认不需要

        option.setOpenGps(true);
        //可选，默认false,设置是否使用gps

        option.setLocationNotify(true);
        //可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果

        option.setIsNeedLocationDescribe(true);
        //可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”

        option.setIsNeedLocationPoiList(true);
        //可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到

        option.setIgnoreKillProcess(false);
        //可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死

        option.setEnableSimulateGps(false);
        //可选，默认false，设置是否需要过滤GPS仿真结果，默认需要

        mLocationClient.setLocOption(option);
    }
}
